<!DOCTYPE html>
<html lang="zh_CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <title>Title</title>
</head>
<body>
<script>
  const promise1 = Promise.resolve(3);
  const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));
  const promise3 = new Promise((resolve, reject) => setTimeout(reject, 1000, 'bar'));
  const promises = [promise3, promise1, promise2, ];
  function add(){

  }

  Promise.myAllSettled = function(promises){
    return new Promise((resolve, reject) => {
      if (!Array.isArray(promises)) {
        reject(new TypeError('promises需要是一个数组'))
      }
      let resolvedCounter = 0
      let promisesLen = promises.length
      let resolvedValues = new Array(promisesLen)
      for (let i = 0; i < promisesLen; i++) {
        Promise.resolve(promises[i]).then(
          value => {
            resolvedCounter++;
            resolvedValues[i] = {value, status: 'fulfilled'}
            if (resolvedCounter === promisesLen) {
              return resolve(resolvedValues)
            }
          },
          reason => {
            resolvedCounter++;
            resolvedValues[i] = {reason, status: 'rejected'}
            if (resolvedCounter === promisesLen) {
              return resolve(resolvedValues)
            }
          }
        )
      }
    })
  }

  Promise.myAllSettled1 = function(promises){
    return Promise.all(promises.map(p=> Promise.resolve(p).then(
      value=> ({value, status: 'fulfilled'}),
      reason=> ({reason, status: 'rejected'})
    )))
  }

  Promise.myAllSettled2 = function(promises){
    return new Promise((resolve, reject) => {
      if (!Array.isArray(promises)) {
        reject(new TypeError('promises需要是一个数组'))
      }
      let promisesLen = promises.length
      let resolvedValues = new Array(promisesLen)
      for (let i = 0; i < promisesLen; i++) {
        promises[i].then( value => {
            resolvedValues[i] = {value, status: 'fulfilled'}
          },
          reason => {
            resolvedValues[i] = {reason, status: 'rejected'}
          }).finally(() => {
          if (!--promisesLen) {
            return resolve(resolvedValues)
          }
        })
      }
    })
  }




  Promise.allSettled(promises).then((results) => results.forEach((result) => console.log(result.status)));
  Promise.myAllSettled(promises).then((results) => results.forEach((result) => console.log(result.status)));
  Promise.myAllSettled1(promises).then((results) => results.forEach((result) => console.log(result.status)));
  Promise.myAllSettled2(promises).then((results) => results.forEach((result) => console.log(result.status)));



</script>
</body>
</html>
